<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>单例模式</title>
</head>

<body>
    <script>
        // 只能实例化一次, 每次返回的实例都是同一个对象

        // 一:
        // var Single = (function () {
        //     var flag
        //     return function (name) {
        //         if (!flag) {
        //             if (new.target !== undefined) {
        //                 this.name = name
        //                 flag = this
        //             } else {
        //                 throw new Error('只能通过new操作符来创建实例对象')
        //             }
        //         }
        //         return flag
        //     }
        // })()

        // var a = new Single('a')
        // var b = new Single('b')
        // console.log(a)
        // console.log(b)
        // console.log(a === b)


        // 二:
        function Single (name) {
            this.name = name
        }

        Single.getInstance = function (name) {
            if (!this.instance) {
                this.instance = new Single(name)
            }
            return this.instance
        }

        var a = Single.getInstance('a')
        var b = Single.getInstance('b')
        console.log(a)
        console.log(b)
        console.log(a === b)



    </script>
</body>

</html>